# -*- coding: utf-8 -*-

import json
import logging

from django.views.generic import TemplateView
from django.utils.encoding import smart_unicode
from django.utils.decorators import method_decorator

from common.show import db as db
from common.utils.decorator import response_wrapper
from common.utils.api import token_required, check_params, mask_string
from common.utils.tz import utc_to_local_str
from common.account.db.account import get_account

_LOGGER = logging.getLogger(__name__)


class ShowView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        items, total_count = db.list_shows(query_dct)

        resp_items = []
        for item in items:
            item.updated_at = utc_to_local_str(item.updated_at)
            item.created_at = utc_to_local_str(item.created_at)
            item_dct = item.as_dict()
            item_dct['order_id'] = str(item_dct['order_id'])
            item_dct['account'] = get_account(item.user_id).as_dict()
            if item_dct['account']['phone'] and item_dct['account']['user_name']:
                if item_dct['account']['user_name'] == item_dct['account']['phone'] or item_dct['account']['user_name'] == item_dct['account']['phone'][2:]:
                    item_dct['account']['user_name'] = mask_string(item_dct['account']['user_name'])
            if not item_dct['account']['phone'] and item_dct['account']['user_name']:
                if len(item_dct['account']['user_name']) == 11 and item_dct['account']['user_name'][0] in ['1', '8']:
                    item_dct['account']['user_name'] = mask_string(item_dct['account']['user_name'])
            resp_items.append(item_dct)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(ShowView, self).dispatch(*args, **kwargs)


class SingleShowView(TemplateView):
    def get(self, req, show_id):
        show = db.get_show_by_id(int(show_id))
        show.updated_at = utc_to_local_str(show.updated_at)
        show.created_at = utc_to_local_str(show.created_at)
        result = show.as_dict()
        result['order_id'] = str(result['order_id'])

        return result

    def post(self, req, show_id):
        return self.put(req, show_id)

    def put(self, req, show_id):
        show_id = int(show_id)
        query_dct = json.loads(smart_unicode(req.body))
        status = int(query_dct.get('status', 0))
        db.verify_show(show_id, status, query_dct.get('verify_comment', ''), query_dct.get('highlight'))
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleShowView, self).dispatch(*args, **kwargs)
